"""赌博实验
原po
https://www.jianshu.com/p/2d919a028600

觉得这个代码挺有意思的 想换一下实验思路
改成理智的赌徒遵循凯利公式下注 看看是什么结果
"""

import random
import pandas as pd


class gambler():
    def __init__(self):
        self.deposit = 1000000  # 百万存款
        self.usury = 0  # 借贷


# 赌场老板
banker = gambler()
# 赌场老板的资本金是一个亿
banker.deposit = 100000000

# player是赌徒本徒
player = gambler()
# 记录每局比赛的输赢
gambling_list = []

# 本游戏赔率固定=2 输赢概率为50% 所以根据凯利公式f=(pb-q)/b = (2 * 50% - 50%) ÷ 2  下注比例应为0.25
kelly_criterion_p = 0.25


def gambling(gambler_a, gambler_b, bet, count):  # a是庄家，b是闲家，bet是当局赌注，count是当前的赌局编号
    point = random.randint(2, 12)  # 骰子点数
    guess = random.randint(0, 1)  # 猜大小，0为小，1为大
    if (point > 7 and guess == 1) or (point <= 7 and guess == 0):  # 猜对了
        player.deposit += bet
        banker.deposit -= bet
        return True
    else:
        player.deposit -= bet
        banker.deposit += bet
        return False


def One_day_gambling():
    count = 0
    while True:
        bet = round(player.deposit, 1) * kelly_criterion_p
        gambling_list.append(gambling(banker, player, bet, count))
        count += 1
        if int(player.deposit) <= 0 or count >= 100:  # 每天最多100局
            break
    return player.deposit  # 返回每天结束时的手头资产


def record_daily_gambling():
    debt = []  # 记录每一天的最终盈亏
    for i in range(3000):
        #  昨天资产
        yesterday = player.deposit
        n = One_day_gambling()
        if n < yesterday:  #亏了
            pass
        m = n - yesterday
        print("今日战绩", m)
        debt.append(m)
        player.deposit = n
        if int(player.deposit) <= 0:  # 一百万输光算破产
            return (sum(debt), i)  # 破产后记下最终输掉的资金，以及破产时间
    return (sum(debt), 3000)  # 一直没有破产的人


def main():
    every_example = pd.DataFrame()
    lost_money = []
    bankrupt_time = []
    for j in range(1000):
        player.deposit = 1000000
        m = record_daily_gambling()
        lost_money.append(m[0])
        bankrupt_time.append(m[1])
        print(j)
    every_example['lost_money'] = lost_money
    every_example['bankrupt_time'] = bankrupt_time
    every_example.to_csv('experiment_data_2.csv', index=False, sep=',')


if __name__ == "__main__":
    main()
